﻿using System;
using System.Collections.Generic;
using EP.Base.BaseService.Manager.Config.Enum;
using EP.Base.BaseService.Manager.Interface;
using EP.Base.BaseService.Manager.Interface.Business;
using EP.Base.BaseService.Manager.Interface.Common;
using EP.Base.BaseService.Manager.Interface.Data;
using EP.Base.BaseService.Manager.Model;
using EP.Base.BaseService.Manager.Model.Entity;

namespace EP.Base.BaseService.Manager.Business.Task
{
    /// <summary>
    /// 执行备份任务-备份是增量的
    /// </summary>
    public class BackupIndexTask : IEsIndexHandelTask
    {
        private readonly IEsClusters _esClusters;
        private readonly IIndexConfigs _indexConfigs;
        private readonly IEsData _esData;
        private readonly ILog _log;
        private readonly IJson _json;
        private readonly IIndexBackupLogs _indexBackupLogs;
        public BackupIndexTask(IEsClusters esClusters, IIndexConfigs indexConfigs, IEsData esData, ILog log, IJson json, IIndexBackupLogs indexBackupLogs)
        {
            _esClusters = esClusters;
            _indexConfigs = indexConfigs;
            _esData = esData;
            _log = log;
            _json = json;
            _indexBackupLogs = indexBackupLogs;
        }

        public bool Exec(EsTaskConfig taskConfig)
        {
            _log.Debug("执行备份任务 id=" + taskConfig.Id);

            //index信息
            var indexConfig = _indexConfigs.Get(taskConfig.IndexConfigId);
            if (indexConfig == null)
            {
                _log.WarnFormat("IndexConfigId={0},未找到对应的indexConfig数据！", taskConfig.IndexConfigId);
                return false;
            }
            //es集群信息
            var esClustersInfo = _esClusters.Get(indexConfig.ClusterId);
            if (esClustersInfo == null)
            {
                _log.WarnFormat("ClusterId={0},未找到对应的esClustersInfo数据！", indexConfig.ClusterId);
                return false;
            }

            //有别名就通过别名找所有索引 没有 就使用前缀
            IEnumerable<string> indices = !string.IsNullOrWhiteSpace(indexConfig.Alias) ? _esData.GetAllIndexByAlias(esClustersInfo.ServiceHostArr, indexConfig.Alias) : new[] {indexConfig.IndexNamePrefix};
            
            var currentTaskConfig = _json.DeserializeObject<BackupIndexTaskConfig>(taskConfig.Configs);

            string snapshotName = currentTaskConfig.SnapshotNamePre + "-" + DateTime.Now.ToString("yyyyMMddHHmmss");
            
            var bkState = EnumIndexBackupLogState.Fail;
            Action<EnumIndexBackupLogState> addlog = state => _indexBackupLogs.Add(new IndexBackupLog
            {
                Repository = currentTaskConfig.Repository,
                SnapshotName = snapshotName,
                CreateTime = DateTime.Now,
                IndexConfigId = taskConfig.IndexConfigId,
                State = (short)state
            });
            try
            {
                //快照所有索引
                var result = _esData.Snapshot(esClustersInfo.ServiceHostArr, currentTaskConfig.Repository, snapshotName,
                    indices);
                if (result)
                    bkState = EnumIndexBackupLogState.Eexecuted;
                addlog(bkState);
                return result;
            }
            catch (Exception)
            {
                addlog(bkState);
                throw;
            }
        }
    }
}
